package com.jcfk.system.service;

import com.jcfk.common.core.constant.Constants;
import com.jcfk.common.security.service.TokenService;
import com.jcfk.system.api.utils.LoginUserInfoUtils;
import com.jcfk.system.domain.dto.SendMsgDTO;
import com.jcfk.system.domain.po.SysInternalMessage;
import com.jcfk.system.domain.query.SysMessageQuery;
import com.jcfk.system.domain.dto.SysInternalMessageDTO;
import com.jcfk.system.dao.SysMessageDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author awei
 * @email 522891237@gqq.com
 * @date 2023-11-27 09:38:04
 */
@Service
public class SysInternalMessageService extends BaseService<SysMessageDao, SysInternalMessage> {

    @Autowired
    private TokenService tokenService;

    /**
     * SysMessage分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<SysInternalMessageDTO> queryByPage(DataPage<SysInternalMessageDTO> page, SysMessageQuery query) {
        query.setRecevieUserId(SecurityUtils.getUserId());
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * 判断SysMessage是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(SysInternalMessageDTO dto) {
        return RetResult.ok();
    }

    /**
     * 插入
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SysInternalMessageDTO insert(SysInternalMessageDTO dto) {

        // 保存
        SysInternalMessage item = new SysInternalMessage();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);

        BeanUtils.copyProperties(item, dto);

        return dto;
    }

    /**
     * 更新
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SysInternalMessageDTO update(SysInternalMessageDTO dto) {

        // 保存
        SysInternalMessage item = new SysInternalMessage();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);
        BeanUtils.copyProperties(item, dto);

        return dto;
    }

    /**
     * 根据批量主键删除(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(SysInternalMessageDTO dto) {

        SysInternalMessage item = new SysInternalMessage();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<SysInternalMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(SysInternalMessage item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());
        item.setLastUpdatedUserName(SecurityUtils.getUserName());
        item.setDeleted(0);

    }

    /**
     * 根据主键获取信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public SysInternalMessageDTO get(String id) {
        // 查询数据
        SysInternalMessageDTO item = this.baseMapper.getMessInfo(id);
        if (item.getReaded().equals(0)) {
            SysInternalMessage sysInternalMessage = this.baseMapper.selectById(id);
            sysInternalMessage.setReaded(1);
            sysInternalMessage.setReadTime(new Date());
            this.baseMapper.updateById(sysInternalMessage);
        }
        return item;
    }


    /**
     * 发送消息
     *
     * @param msgInfo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<SysInternalMessage> SendMessage(SendMsgDTO msgInfo) {

        List<SysInternalMessage> list = new ArrayList<>();

        // 组装消息
        for (String userId : msgInfo.getReceiveUserIds()) {
            SysInternalMessage message = new SysInternalMessage();
            message.setMsgType(msgInfo.getMsgType());
            message.setTitle(msgInfo.getTitle());
            message.setUrl(msgInfo.getUrl());
            message.setMsgBody(msgInfo.getMsgBody());
            message.setSendUserId(msgInfo.getSendUserId());
            message.setSendTime(new Date());
            message.setRecevieUserId(userId);
            message.setReaded(Constants.NO);
            message.setEnabled(Constants.YES);
            message.setSendTime(new Date());
            message.setSendUserId(SecurityUtils.getUserId());
            this.setDefaultValue(message);
            list.add(message);
        }

        // 入库
        if (list.size() > 0) this.saveBigBatch(list);

        return list;
    }


    /**
     * 获取n条未读消息
     *
     * @param query
     * @return
     */
    public List<SysInternalMessageDTO> getUnReadByRecevier(SysMessageQuery query) {
        query.setRecevieUserId(LoginUserInfoUtils.getUserId());
        return baseMapper.getUnRead(query);
    }

    /**
     * 消息管理  获取当前用户未读消息数量
     *
     * @return
     */
    public Integer getcount() {
        QueryWrapper<SysInternalMessage> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.in("recevie_user_id", LoginUserInfoUtils.getUserId());
        messageQueryWrapper.eq("readed", Constants.NO);

        // 获取数量
        return this.count(messageQueryWrapper);
    }

    // 获取报工超计划报警消息
    public Integer getReportAlarmMessage() {
        QueryWrapper<SysInternalMessage> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.eq("title", "报工超出计划报警");
        messageQueryWrapper.eq("readed", Constants.NO);
        // 获取数量
        return this.count(messageQueryWrapper);
    }

    public Integer getreadcount() {
        QueryWrapper<SysInternalMessage> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.in("recevie_user_id", LoginUserInfoUtils.getUserId());
        messageQueryWrapper.eq("readed", Constants.YES);

        // 获取数量
        return this.count(messageQueryWrapper);
    }
}

